package com.websocket.socket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.websocket.vo.Message;

@ServerEndpoint("/chatSocket")
public class ChatWebSocket {
	private String username;
	private static List<Session> session= new ArrayList<>();
	private static List<String> names=new ArrayList<>();
	
	@OnOpen
	public void open(Session session){
		String queryString=session.getQueryString();
		username=queryString.split("=")[1];
		System.out.println(username);
		
		this.session.add(session);
		this.names.add(username);
		
		String msg="欢迎" + this.username + "进入聊天室";
		
		Message message=new Message();
		message.setWelcome(msg);
		message.setUsername(this.names);
		
		this.broadcast(this.session,message.toJson());
		
	}
	
	private void broadcast(List<Session> ss, String jsonObject) {
		// TODO Auto-generated method stub
	    for(Iterator iterator=ss.iterator();iterator.hasNext();){
	    	Session session=(Session) iterator.next();
	    	try {
				session.getBasicRemote().sendText(jsonObject);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
	}
	
	@OnClose
	public void close(Session session){
		this.session.remove(session);
		this.names.remove(username);
		
		String msg=this.username + "离开聊天室";
		Message message=new Message();
		message.setWelcome(msg);
		message.setUsername(this.names);
		
		broadcast(this.session, message.toJson());
	}
	
	@OnMessage
    public void message(Session session,String msg){
        
    	Message message=new Message();
		message.setContent(this.username, msg);
    	
    	broadcast(this.session, message.toJson());
    }
}
